import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);
const routes = [
  { path: "/", redirect: "/login" },
  { path: "/login", component: () => import("@/views/login.vue") },
  {
    path: "/layout",
    component: () => import("@/views/layout.vue"),
    redirect: "/layout/index",
    children: [
      { path: "index", component: () => import("@/views/index") },
      { path: "articleList", component: () => import("@/views/articleList") },
      { path: "articleAdd", component: () => import("@/views/articleAdd") },
    ],
  },
];

const router = new VueRouter({ routes });

//路由守卫配置
router.beforeEach((to, from, next) => {
  let token = localStorage.getItem("back-token");
  //用户没登陆 ,并且访问除了login的网页 ,让其跳回登录页先登录
  if (to.path !== "/login" && !token) {
    next("/login");
  } else {
    //登陆后 不让用户直接访问登录页面
    if (to.path == "/login" && token) {
      next("/layout");
    } else {
      next();
    }
  }
});

export default router;
